package com.zcl.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.zcl.bean.Task;
import com.zcl.logic.MainService;
import com.zcl.utils.NqLog;
import com.zcl.utils.NqUtil;
import com.zcl.utils.Value;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.text.TextUtils;

public class NqUtil {
    /**
     * 文件是否存在
     * 
     * @return
     */
    public static boolean fileExists(String path) {
        if (TextUtils.isEmpty(path)) {
            return false;
        }
        File file = new File(path);
        return file.exists();
    }
    
    /**
     * 得到当前使用的接入点的代理地址
     * 
     * @param context
     * @return
     */
    public static Proxy getApnProxy(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (ni.isConnected()) { // 如果有wifi连接，则选择wifi，不返回代理
            if (Value.printLog) {
                NqLog.d("getApnProxy ni.isConnected()");
            }
            return null;
        } else {
            Cursor c = NqUtil.getCurrentApn(context); // 得到默认apn
            if (c == null) {
                if (Value.printLog) {
                    NqLog.d("getApnProxy getCurrentApn is null");
                }
                return null;
            }
            if (Value.printLog) {
                NqLog.d("getApnProxy getCurrentApn count: " + c.getCount());
            }
            if (c.getCount() > 0) {
                c.moveToFirst();
                // long id = c.getLong(c.getColumnIndex("_id"));
                // if(Value.printLog){NqLog.d("current apn id",""+id);}
                String proxy = c.getString(c.getColumnIndex("proxy")); // 得到代理
                String port = c.getString(c.getColumnIndex("port")); // 得到断开号
                c.close();

                if (Value.printLog) {
                    NqLog.d("getApnProxy getCurrentApn proxy: " + proxy + " port: " + port);
                }

                // ZLog.writeLog("proxy:"+proxy+" port "+port);
                if (proxy != null && !proxy.equals("")) { // 代理地址不为空
                    if (port != null && !port.equals("")) {
                        if (isIpAddress(proxy)) {
                            return new Proxy(Proxy.Type.HTTP, InetSocketAddress.createUnresolved(proxy, Integer.valueOf(port)));
                        } else {
                            return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxy, Integer.valueOf(port)));
                        }
                    } else {
                        return null;
                    }
                }
            }
            c.close();
        }
        return null;
    }
    
    /**
     * 得到手机上面当前默认使用的接入点
     * 
     * @param context
     * @return
     */
    public static Cursor getCurrentApn(Context context) {
        return context.getContentResolver().query(Uri.parse("content://telephony/carriers/preferapn"), null, null, null, null);
    }
    
    /**
     * 判断是否是合法的ip地址
     * @param host
     * @return
     */
    public static boolean isIpAddress(String host) {
        String ip = host;
        String t[] = host.split("://");
        if (t.length > 1) {
            ip = t[1];
        } else {
            t = host.split("//");
            if (t.length > 1) {
                ip = t[1];
            }
        }
        int len = ip.length();

        // 如果位数不对，直接返回false
        if (len < 7 || len > 15) {
            return false;
        }

        t = ip.split("\\.");

        if (t.length != 4)
            return false;

        if (!isIpNumberValid(t[0]))
            return false;
        else if (!isIpNumberValid(t[1]))
            return false;
        else if (!isIpNumberValid(t[2]))
            return false;
        else if (!isIpNumberValid(t[3]))
            return false;

        return true;
    }
    
    /**
     * 判断字符串转成整数是否是 0-255
     * @param str
     * @return
     */
    private static boolean isIpNumberValid(String str) {
        if (str.length() == 0)
            return false;

        int v = -1;
        try {
            v = Integer.parseInt(str);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        if (v >= 0 && v <= 255)
            return true;
        return false;
    }
    
    /**
     * 得到手机当前网络是否可用
     * 
     * @param context
     * @return
     */
    public static boolean getNetworkEnable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        return (null != activeNetInfo);
    }
    
    /**
     * Reason::http://docs.oracle.com/javase/1.5.0/docs/guide/net/http-keepalive.html Spec::What can
     * you do to help with Keep-Alive?
     */
    public static void helpHttpKeepAlive(HttpURLConnection connection) {
        try {
            ((HttpURLConnection) connection).getResponseCode();
            InputStream es = ((HttpURLConnection) connection).getErrorStream();
            if (es == null) {
                return;
            }
            // read the response body
            byte buf[] = new byte[1024];
            int ret = 0;
            while ((ret = es.read(buf)) > 0) {
            }
            // close the errorstream
            es.close();
        } catch (IOException ex) {
            // deal with the exception
        }
    }
    
    /**
     * 删除指定文件
     * 
     * @param strFileName
     */
    public static void deleteFile(String strFileName) {
        if (TextUtils.isEmpty(strFileName)) {
            return;
        }
        File file = new File(strFileName);
        if (file.exists()) {
            file.delete();
        }
    }
    
    /**
     * 删除文件夹里面的所有文件，保留文件夹
     * 
     * @param path
     *            String 文件夹路径 如
     */
    public static void delAllFile(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return;
        }
        if (!file.isDirectory()) {
            return;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);// 再删除空文件夹
            }
        }
    }
    
    /**
     * 删除文件夹所有内容以及文件夹
     * 
     * @param folderPath
     *            String 文件夹路径及名称
     */
    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); // 删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            java.io.File myFilePath = new java.io.File(filePath);
            myFilePath.delete(); // 删除空文件夹

        } catch (Exception e) {
            e.printStackTrace();

        }
    }
    
    /**
     * dip转换为px
     * 
     * @param context
     * @param dip
     * @return
     */
    public static int convertDIP2PX(Context context, int dip) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dip * scale + 0.5f * (dip >= 0 ? 1 : -1));
    }
    
    /**
     * 高效率获得指定尺寸的图片
     * 
     * @param pFileParth
     * @param width
     *            <=0 将返回原图
     * @param height
     *            <=0 将返回原图
     * @return 参数不合法或无法解码时，将返回null
     */
    public static Bitmap getBitmap(String pFileParth, int width, int height) {
        if (TextUtils.isEmpty(pFileParth)) {
            return null;
        }
        if (Value.printLog) {
            NqLog.d("getBitmap", "file::" + pFileParth);
        }
        File _File = new File(pFileParth);
        FileInputStream _FileInputStream = null;
        try {
            _FileInputStream = new FileInputStream(_File);
            Bitmap bitmap = getBitmap(width, height, _FileInputStream.getFD());
            _FileInputStream.close();
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 
     * @param width
     *            <=0 将返回原图
     * @param height
     *            <=0 将返回原图
     * @param pFileDescriptor
     * @return
     */
    private static Bitmap getBitmap(int width, int height, FileDescriptor pFileDescriptor) {
        if (pFileDescriptor == null) {
            return null;
        }

        BitmapFactory.Options options = new BitmapFactory.Options();
        // designated original size first
        options.inSampleSize = 1;
        // 只进行大小判断
        options.inJustDecodeBounds = true;
        // 调用此方法得到options得到图片的大小
        BitmapFactory.decodeFileDescriptor(pFileDescriptor, null, options);
        // 我们的目标是在800pixel的画面上显示。
        // 所以需要调用computeSampleSize得到图片缩放的比例
        options.inSampleSize = (width <= 0 || height <= 0) ? 1 : computeSampleSize(options, width, height);
        // OK,我们得到了缩放的比例，现在开始正式读入BitMap数据
        options.inJustDecodeBounds = false;
        options.inDither = false;
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;

        // 根据options参数，减少所需要的内存
        return BitmapFactory.decodeFileDescriptor(pFileDescriptor, null, options);
    }
    
    /**
     * 对图片的大小进行判断，并得到合适的缩放比例，比如2即1/2,3即1/3
     * @param options
     * @param width
     * @param height
     * @return
     */
    static int computeSampleSize(BitmapFactory.Options options, int width, int height) {
        int w = options.outWidth;
        int h = options.outHeight;
        int candidateW = w / width;
        int candidateH = h / height;
        int candidate = Math.max(candidateW, candidateH);
        if (candidate == 0)
            return 1;
        if (candidate > 1) {
            if ((w > width) && (w / candidate) < width)
                candidate -= 1;
        }
        if (candidate > 1) {
            if ((h > height) && (h / candidate) < height)
                candidate -= 1;
        }
        return candidate;
    }
    
    /**
     * Drawable转换为byte
     * @param drawable
     * @return
     */
    public static byte[] drawableConvertByte(Drawable drawable)
    {
    	if (drawable == null) {
			return null;
		}
    	Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
		byte[] bitmapdata = stream.toByteArray();
		return bitmapdata;
    }
    
    /**
     * byte[]转换为Drawable
     * @param bytes
     * @return
     */
    public static Drawable byteConvertDrawable(byte[] bytes)
    {
    	if (bytes == null || bytes.length == 0) {
			return null;
		}
    	ByteArrayInputStream is = new ByteArrayInputStream(bytes);
		Drawable drawable = Drawable.createFromStream(is, "png");
    	return drawable;
    }
    
    /**
     * bitmap转换为Drawable
     * @param context
     * @param bitmap
     * @return
     */
    public static Drawable bitmapConvertDrawable(Context context, Bitmap bitmap)
    {
    	Drawable drawable = new BitmapDrawable(context.getResources(), bitmap);
    	return drawable;
    }
    
    public static String getFormatChineseTime(Context context, String time) {
        String ret = time;
        final String DATE_FORMAT = "yyyy-MM-dd HH:mm";

        if (TextUtils.isEmpty(time) || DATE_FORMAT.length() > time.length()) {
            return time;
        }
        SimpleDateFormat sdf1 = new SimpleDateFormat(DATE_FORMAT);
        try {
            Date d = sdf1.parse(time);
            String format = context.getString(com.zcl.iweibo.R.string.memo_dateformat04);
            SimpleDateFormat sdf2 = new SimpleDateFormat(format);
            ret = sdf2.format(d);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return ret;
    }
}
